package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.CommonAdapter;
import com.github.postsanf.yinian.adapter.MapLocationListAdapter;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.LocalViewHolder;
import com.github.postsanf.yinian.ynlist.EndlessRecyclerOnScrollListener;
import com.github.postsanf.yinian.ynlist.LoadingFooter;
import com.github.postsanf.yinian.ynlist.RecyclerViewStateUtils;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

public class ImageLocationEditActivity extends BaseActivity implements View.OnClickListener, PoiSearch.OnPoiSearchListener {
    // , PopListPoiSearchNew.OnImageDirSelected,LocationSource, AMapLocationListener,
    private RecyclerView rv_map_location;
    private MapLocationListAdapter adapter;
    private List<PoiItem> poiItemslist = new ArrayList<>();
    private List<PoiItem> poiSearchslist = new ArrayList<>();
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    private int currentPage = 1;
    private PoiSearch.Query query;
    private PoiResult poiResult;
    private ProgressDialog mProgressDialog;
    private boolean isBottom;
    //    private MapView mMapView;
//    private AMap aMap;
    private EditText labET;
    private ImageView labClear;
    private LinearLayout rl_pop_top;
    public static boolean mainLocation;
    private long fristtime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fristtime = System.currentTimeMillis();
        registerBoradcastReceiver();
        setContentView(R.layout.yn_location_edit);
        initView(savedInstanceState);
        initLocation();
//        initListDirPopupWindw();
    }

    // 广播接收
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionCloseAlbum:
                    int noClear = intent.getExtras().getInt(ACTIONs.aIsClearSelect);
                    if (1 == noClear) {
                        finish();
                    }
                    break;
            }
        }
    };

    //注册广播
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionCloseAlbum);
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

//    OnLocationChangedListener mListener;
//    AMapLocationClient mlocationClient;
//    AMapLocationClientOption mlocationOption;

//    /**
//     * 激活定位
//     */
//    @Override
//    public void activate(OnLocationChangedListener listener) {
//        mListener = listener;
//        if (mlocationClient == null) {
//            mlocationClient = new AMapLocationClient(this);
//            mlocationOption = new AMapLocationClientOption();
//            //设置定位回调监听
//            mlocationClient.setLocationListener(this);
//            //设置为高精度定位模式
//            mlocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//            //设置定位参数
//            mlocationClient.setLocationOption(mlocationOption);
//            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
//            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
//            // 在定位结束后，在合适的生命周期调用onDestroy()方法
//            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//            mlocationClient.startLocation();//启动定位
//        }
//    }

//    /**
//     * 停止定位
//     */
//    @Override
//    public void deactivate() {
//        mListener = null;
//        if (mlocationClient != null) {
//            mlocationClient.stopLocation();
//            mlocationClient.onDestroy();
//        }
//        mlocationClient = null;
//    }

    //    @Override
//    public void onLocationChanged(AMapLocation amapLocation) {
//        if (mListener != null && amapLocation != null) {
//            if (amapLocation != null
//                    && amapLocation.getErrorCode() == 0) {
//                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
//            } else {
//                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
//                Log.e("AmapErr", errText);
//            }
//        }
//    }
    private ListView lv_album_list_dir;
    private CommonAdapter cadapter;

    private void initView(Bundle savedInstanceState) {
        if (getIntent() != null) {
            mainLocation = getIntent().getBooleanExtra("mainLocation", false);
        }
        findViewById(R.id.iv_back).setOnClickListener(this);
        rl_pop_top = (LinearLayout) findViewById(R.id.rl_pop_top);
        rv_map_location = (RecyclerView) findViewById(R.id.rv_edit_location);
        rv_map_location.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rv_map_location.setItemAnimator(new DefaultItemAnimator());
//        View header = LayoutInflater.from(this).inflate(R.layout.imagelocationedit_header, rv_map_location, false);
//        MapContainer map_container = (MapContainer) header.findViewById(R.id.map_container);
//        map_container.setScrollView(rv_map_location);
//        mMapView = (MapView) header.findViewById(R.id.location_mapview);
//        mMapView.onCreate(savedInstanceState);
//        if (aMap == null) {
//            aMap = mMapView.getMap();
//        }
//        aMap.setLocationSource(this);
//        aMap.setMyLocationEnabled(true);
//        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
//        adapter.setHeaderView(header);
        adapter = new MapLocationListAdapter(this, poiItemslist, "", mainLocation);
        rv_map_location.setAdapter(adapter);
        rv_map_location.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadNextPage(View view) {
                super.onLoadNextPage(view);
                if (isBottom) {
                    return;
                }
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(rv_map_location);
                if (state == LoadingFooter.State.Loading) {
                    return;
                }
                RecyclerViewStateUtils.setFooterViewState(ImageLocationEditActivity.this, rv_map_location, 10, LoadingFooter.State.Loading, null);
                rv_map_location.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (pamapLocation != null) {
                            query = new PoiSearch.Query("", "", CityCode);
                            query.setPageSize(10);
                            query.setPageNum(currentPage);// 设置查第一页
                            currentPage++;
                            poiSearch = new PoiSearch(ImageLocationEditActivity.this, query);
                            poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(pamapLocation
                                    .getLatitude(), pamapLocation.getLongitude()), 1000));
                            poiSearch.setOnPoiSearchListener(ImageLocationEditActivity.this);
                            poiSearch.searchPOIAsyn();
                        }
                    }
                }, 500);
            }
        });
        lv_album_list_dir = (ListView) findViewById(R.id.lv_album_list_dir);
        cadapter = new CommonAdapter<PoiItem>(this, poiSearchslist,
                R.layout.map_location_item, 1) {
            @Override
            public void convert(LocalViewHolder helper, PoiItem item, Boolean isFirst) {
                if (isFirst) {
                    helper.getView(R.id.normal).setVisibility(View.GONE);
                    helper.getView(R.id.frist).setVisibility(View.VISIBLE);
                    helper.setText(R.id.location_item_creattt, labET.getText().toString());
                    helper.getView(R.id.frist).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mainLocation) {
                                startActivity(new Intent(ImageLocationEditActivity.this, LocationEditActivity.class).putExtra("locationtx", labET.getText().toString()));
                            } else {
                                sendBroadcast(new Intent("updatelocationtx").putExtra("locationtx", labET.getText().toString()));
                            }
                            finish();
                        }
                    });
                } else {
                    helper.getView(R.id.normal).setVisibility(View.VISIBLE);
                    helper.getView(R.id.frist).setVisibility(View.GONE);
                    helper.setText(R.id.location_item_tt, item.getTitle());
                    helper.setText(R.id.location_item_des, item.getSnippet());
                    final String title = item.getTitle();
                    helper.getView(R.id.normal).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mainLocation) {
                                startActivity(new Intent(ImageLocationEditActivity.this, LocationEditActivity.class).putExtra("locationtx", title));
                            } else {
                                sendBroadcast(new Intent("updatelocationtx").putExtra("locationtx", title));
                            }
                            finish();
                        }
                    });
                }
            }
        };
        lv_album_list_dir.setAdapter(cadapter);
        labET = (EditText) findViewById(R.id.publabel_edit);
        labClear = (ImageView) findViewById(R.id.publabel_clear);
        labClear.setOnClickListener(this);
        labET.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                PoiSearch.Query query = new PoiSearch.Query(s.toString(), "", CityCode);
                query.setPageSize(15);
                query.setPageNum(1);
                PoiSearch poiSearch = new PoiSearch(ImageLocationEditActivity.this, query);
                poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
                    @Override
                    public void onPoiSearched(PoiResult poiResult, int rCode) {
                        if (rCode == 1000) {
                            // 搜索POI的结果
                            if (poiResult != null && poiResult.getQuery() != null) {
                                final int resultPages = poiResult.getPageCount();
                                final List<PoiItem> poiItems = poiResult.getPois();
                                if (poiItems != null && poiItems.size() > 0) {
                                    poiSearchslist.clear();
                                    poiSearchslist.addAll(poiItems);
                                    cadapter.notifyDataSetChanged();
//                                    mListImageDirPopupWindow.setAdapterNotify();
//                                    mListImageDirPopupWindow.dismiss();
//                                    mListImageDirPopupWindow.showAsDropDown(rl_pop_top, 0, 0);
                                }
                            }
                        } else {
                            Log.i("xjs", "rcode==>" + rCode);
                        }
                    }

                    @Override
                    public void onPoiItemSearched(PoiItem poiItem, int i) {

                    }
                });
                poiSearch.searchPOIAsyn();
                if (s.length() > 0) {
                    labClear.setVisibility(View.VISIBLE);
//                    if (!mListImageDirPopupWindow.isShowing())
//                    mListImageDirPopupWindow.showAsDropDown(rl_pop_top, 0, 0);
                    lv_album_list_dir.setVisibility(View.VISIBLE);
                    rv_map_location.setVisibility(View.GONE);
                    cadapter.notifyDataSetChanged();
                } else {
                    labClear.setVisibility(View.INVISIBLE);
//                    mListImageDirPopupWindow.dismiss();
                    lv_album_list_dir.setVisibility(View.GONE);
                    rv_map_location.setVisibility(View.VISIBLE);
                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            public void afterTextChanged(Editable s) {
//                if(delayRun!=null){
//                    //每次editText有变化的时候，则移除上次发出的延迟线程
//                    handler.removeCallbacks(delayRun);
//                }
//                //延迟800ms，如果不再输入字符，则执行该线程的run方法
//                handler.postDelayed(delayRun, 800);

            }
        });
    }

//    private Runnable delayRun = new Runnable() {

//        @Override
//        public void run() {
//            Log.i("xjs", "labET.getText===>" + labET.getText().toString().trim());
//            PoiSearch.Query query = new PoiSearch.Query(labET.getText().toString(), "", CityCode);
//            query.setPageSize(15);
//            query.setPageNum(1);
//            PoiSearch poiSearch = new PoiSearch(ImageLocationEditActivity.this, query);
//            poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
//                @Override
//                public void onPoiSearched(PoiResult poiResult, int rCode) {
//                    if (rCode == 1000) {
//                        // 搜索POI的结果
//                        if (poiResult != null && poiResult.getQuery() != null) {
//                            final int resultPages = poiResult.getPageCount();
//                            final List<PoiItem> poiItems = poiResult.getPois();
//                            Log.i("xjs", "searchsize==>" + poiItems.size());
//                            if (poiItems != null && poiItems.size() > 0) {
//                                poiSearchslist.clear();
//                                poiSearchslist.addAll(poiItems);
//                                mListImageDirPopupWindow.setAdapterNotify();
//                                mListImageDirPopupWindow.showAsDropDown(rl_pop_top, 0, 0);
//                            }
//                        }
//                    } else {
//                        Log.i("xjs", "rcode==>" + rCode);
//                    }
//                }
//
//                @Override
//                public void onPoiItemSearched(PoiItem poiItem, int i) {
//
//                }
//            });
//            poiSearch.searchPOIAsyn();
//        }
//    };
//    private Handler handler = new Handler();
//
//    private PopListPoiSearchNew mListImageDirPopupWindow;

//    private void initListDirPopupWindw() {
//        mListImageDirPopupWindow = new PopListPoiSearchNew(
//                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
//                poiSearchslist, LayoutInflater.from(this)
//                .inflate(R.layout.yn_album_list_dir, null));
//        mListImageDirPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//
//            }
//        });
//        mListImageDirPopupWindow.setOnImageDirSelected(this);
//    }

//    @Override
//    public void selected(PoiItem floder) {
//        sendBroadcast(new Intent("updatelocationtx").putExtra("locationtx", floder.getTitle()));
//        finish();
//    }

    private void initLocation() {
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(mAMapLocationListener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setOnceLocationLatest(true);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setMockEnable(false);
        mLocationOption.setHttpTimeOut(20000);
        mLocationOption.setLocationCacheEnable(false);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_DATA);
    }


    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        if (rCode == 1000) {
            // 搜索POI的结果
            if (result != null && result.getQuery() != null) {
                mProgressDialog.dismiss();
                // 是否是同一条
                if (result.getQuery().equals(query)) {
                    poiResult = result;
//                    final int resultPages = poiResult.getPageCount();
                    final List<PoiItem> poiItems = poiResult.getPois();
//                    Log.i("xjs", "poiItems.sssize==>" + poiItems.size());
                    if (poiItems != null && poiItems.size() > 0) {
                        poiItemslist.addAll(poiItems);
                        View view = getLayoutInflater().inflate(R.layout.map_location_item_header, null);
                        TextView citytv = (TextView) view.findViewById(R.id.location_item_city);
                        citytv.setText(city);
                        view.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (mainLocation) {
                                    startActivity(new Intent(ImageLocationEditActivity.this, LocationEditActivity.class).putExtra("locationtx", city));
                                } else {
                                    sendBroadcast(new Intent("updatelocationtx").putExtra("locationtx", city));
                                    finish();
                                }
                            }
                        });
                        adapter.setHeaderView(view);
                        adapter.notifyDataSetChanged();
                        if (poiItems.size() == 0) {
                            isBottom = true;
                            RecyclerViewStateUtils.setFooterViewState(this, rv_map_location, 10, LoadingFooter.State.TheEnd, null);
                        } else {
                            RecyclerViewStateUtils.setFooterViewState(rv_map_location, LoadingFooter.State.Normal);
                        }
                    }
                }
            }
        } else {
            Log.i("xjs", "rcode==>" + rCode);
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem result, int code) {
        // Log.i("xjs", "地址：" + result.getSnippet());
    }

    String city;
    PoiSearch poiSearch;
    String CityCode;
    AMapLocation pamapLocation;
    AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    pamapLocation = amapLocation;
//                    String address = amapLocation.getAddress();
                    city = amapLocation.getCity();
//                    String Street = amapLocation.getStreet() + amapLocation.getStreetNum();//街道信息
                    CityCode = amapLocation.getCityCode();
                    query = new PoiSearch.Query("", "", CityCode);
                    query.setPageSize(10);
                    query.setPageNum(0);// 设置查第一页
                    mProgressDialog.dismiss();
                    poiSearch = new PoiSearch(ImageLocationEditActivity.this, query);
                    poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(amapLocation
                            .getLatitude(), amapLocation.getLongitude()), 1000));
                    poiSearch.setOnPoiSearchListener(ImageLocationEditActivity.this);
                    poiSearch.searchPOIAsyn();
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                    Toast.makeText(ImageLocationEditActivity.this, "定位失败!", Toast.LENGTH_SHORT).show();
                    mProgressDialog.dismiss();
                }
            } else {
                Toast.makeText(ImageLocationEditActivity.this, "定位失败!", Toast.LENGTH_SHORT).show();
                mProgressDialog.dismiss();
            }
        }
    };


    public void ToSetDialog() {
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setCancelable(false);
        final android.support.v7.app.AlertDialog dlg = builder.create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.pub_dialog);
        window.setBackgroundDrawableResource(R.color.transparent);
        WindowManager.LayoutParams layout = dlg.getWindow().getAttributes();
        layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 35 * 2);
        dlg.getWindow().setAttributes(layout);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("提示");
        TextView content = (TextView) window.findViewById(R.id.pp_content);
        content.setText("是否放弃编辑？");
        TextView cancel = (TextView) window
                .findViewById(R.id.btn_cancel);
        cancel.setText("继续编辑");
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView ok = (TextView) window.findViewById(R.id.btn_ok);
        ok.setText("确定");
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (mainLocation) {
            if (new Long(System.currentTimeMillis() - fristtime) > 4900) {
                ToSetDialog();
            } else {
                finish();
            }
        } else {
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                if (mainLocation) {
                    if (new Long(System.currentTimeMillis() - fristtime) > 4900) {
                        ToSetDialog();
                    } else {
                        finish();
                    }
                } else {
                    finish();
                }
                break;
            case R.id.publabel_clear:
                labET.setText("");
//                mListImageDirPopupWindow.dismiss();
                break;
            default:
                break;
        }

    }


    // 友盟统计
    public void onResume() {
        super.onResume();
//        mMapView.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
//        mMapView.onPause();
        mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mMapView.onDestroy();
//        if (null != mlocationClient) {
//            mlocationClient.onDestroy();
//        }
        if (mainLocation) {
            SelectedImg.mSelectedImage.clear();
            AiteSelectActivity.phoneNames.clear();
            MicAddActivity.mMp3FileName = "";
            MainActivity.mp3IsExist = false;
            MainActivity.micUrl = "";
            MainActivity.micpath = "";
            MainActivity.locationTx = "";
        }
        mLocationClient.onDestroy();
        this.unregisterReceiver(mBroadcastReceiver);
    }

//    @Override
//    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
//        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
//        mMapView.onSaveInstanceState(outState);
//    }
}
